package com.eclink.asset.asset.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eclink.asset.domain.AssetCategory;
import com.eclink.asset.asset.domain.dao.AssetItem;
import com.eclink.asset.domain.dto.AssetInventorySaveDTORangeForm;
import com.eclink.asset.mapper.AssetItemMapper;
import com.eclink.asset.pojo.query.AssetItemQuery;
import com.eclink.asset.service.AssetCategoryService;
import com.eclink.asset.sys.service.SysUserService;
import com.eclink.asset.warehouse.service.WarehouseService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 资产清单表Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class AssetItemService {

    @Resource
    private AssetItemMapper assetItemMapper;

    @Resource
    private AssetCategoryService assetCategoryService;

    @Resource
    private SysUserService userService;

    private static final String PREV_CODE = "ZC";

    private static final int NUMBER_APPEND_LENGTH = 6;
    @Autowired
    private WarehouseService warehouseService;

    private String getZeroString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < NUMBER_APPEND_LENGTH; i++) {
            sb.append("0");
        }
        return sb.toString();
    }

    private String getNumber() {

        String numberPrefix = PREV_CODE;

        QueryWrapper<AssetItem> qw = new QueryWrapper<>();
        qw.likeRight("number", numberPrefix);
        qw.last("limit 1");
        qw.orderByDesc("number");
        AssetItem item = assetItemMapper.selectOne(qw);
        int orderNo = 1;

        if (item != null) {
            String lastNumber = item.getNumber();
            int numberLength = lastNumber.length();
            orderNo = Integer.parseInt(lastNumber.substring(numberLength - NUMBER_APPEND_LENGTH, numberLength)) + 1;
        }
        String numberAppend = getZeroString() + orderNo;
        numberAppend = numberAppend.substring(numberAppend.length() - NUMBER_APPEND_LENGTH);
        return numberPrefix + numberAppend;
    }

    /**
     * 查询资产清单表
     *
     * @param id 资产清单表主键
     * @return 资产清单表
     */
    public AssetItem selectById(Long id) {
        AssetItem res = assetItemMapper.selectById(id);
        AssetCategory cate = assetCategoryService.selectById(res.getCategoryId());
        if (cate != null) {
            res.setCategoryName(cate.getName());
        }
        if (res.getAdminId() != null && res.getAdminId() != 0) {
            res.setAdminName(userService.getUserNameById(res.getAdminId()));
        }
        return res;
    }

    /**
     * 查询资产清单表列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 资产清单表
     */
    public List<AssetItem> selectList(AssetItemQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<AssetItem> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);

        if (query.getState()!=null) {
            qw.eq("state",query.getState());
        }
        if (StringUtils.isNotBlank(query.getValue())) {
            qw.like(query.getField(),query.getValue());
        }
        qw.orderByDesc("id");
        List<AssetItem> list = assetItemMapper.selectList(qw);
        this.fillList(list);
        return list;
    }

    /**
     * 查询资产清单表列表
     * ids IDs
     *
     * @return 资产清单表
     */
    public List<AssetItem> listByIds(Long[] ids) {
        QueryWrapper<AssetItem> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        qw.in("id", Arrays.asList(ids));
        qw.orderByDesc("id");
        List<AssetItem> list = assetItemMapper.selectList(qw);
        this.fillList(list);
        return list;
    }

    /**
     * 查询资产清单表列表
     *
     * @param tag 标签
     * @return 资产清单表
     */
    @Cacheable(value="assetByTag", key="#tag")
    public List<AssetItem> selectByRfid(String tag) {

        QueryWrapper<AssetItem> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        qw.eq("rfid",tag);
        qw.orderByDesc("id");
        List<AssetItem> list = assetItemMapper.selectList(qw);
        this.fillList(list);
        return list;
    }

    private void fillList(List<AssetItem> list) {
        for(AssetItem item : list) {

            item.setCategoryName(assetCategoryService.selectNameById(item.getCategoryId()));
            item.setWarehouseName(warehouseService.getWarehouseNameById(item.getWarehouseId()));

            if (item.getAdminId()!= null && item.getAdminId()> 0) {
                item.setAdminName(userService.getUserNameById(item.getAdminId()));
            }
            if (item.getUserId()!= null && item.getUserId()> 0) {
                item.setUserName(userService.getUserNameById(item.getUserId()));
            }
        }
    }

    public List<AssetItem> selectListAll(Map<String, Object> params) {
        LambdaQueryWrapper<AssetItem> qw = new LambdaQueryWrapper<>();
        qw.eq(AssetItem::getDelFlag,0);
        Integer warehouseId = (Integer) params.get("warehouseId");
        if (warehouseId != null && warehouseId > 0) {
            qw.eq(AssetItem::getWarehouseId, warehouseId);
        }
        Integer categoryId = (Integer) params.get("categoryId");
        if (categoryId != null && categoryId > 0) {
            qw.eq(AssetItem::getCategoryId, categoryId);
        }
        Integer status = (Integer) params.get("status");
        if (status != null && status > 0) {
            qw.eq(AssetItem::getState, status);
        }
        Integer companyId = (Integer) params.get("companyId");
        if (companyId != null && companyId > 0) {
            qw.eq(AssetItem::getCompanyId, companyId);
        }
        Integer deptId = (Integer) params.get("deptId");
        if (deptId != null && deptId > 0) {
            qw.eq(AssetItem::getDeptId, deptId);
        }
        Integer adminId = (Integer) params.get("adminId");
        if (adminId != null && adminId > 0) {
            qw.eq(AssetItem::getAdminId, adminId);
        }

        List<AssetItem> list = assetItemMapper.selectList(qw);
        this.fillList(list);
        return list;
    }

    /**
     * 新增资产清单表
     *
     * @param assetItem 资产清单表
     * @return 结果
     */
    public int insert(AssetItem assetItem) {
        assetItem.setDelFlag(0);
        if (StringUtils.isBlank(assetItem.getNumber())) {
            assetItem.setNumber(getNumber());
        }
        return assetItemMapper.insert(assetItem);
    }

    /**
     * 修改资产清单表
     *
     * @param assetItem 资产清单表
     * @return 结果
     */
    public int update(AssetItem assetItem) {
        return assetItemMapper.updateById(assetItem);
    }

    /**
     * 批量删除资产清单表
     *
     * @param ids 需要删除的资产清单表主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
        for(Long id : ids) {
            assetItemMapper.deleteById(id);
        }
        return 1;
    }

    /**
     * 删除资产清单表信息
     *
     * @param id 资产清单表主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return assetItemMapper.deleteById(id);
    }

    public int getCount(Long categoryId) {
        QueryWrapper<AssetItem> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        qw.eq("category_id",categoryId);
        return assetItemMapper.selectCount(qw);
    }

    public BigDecimal getSum(Long categoryId) {
        QueryWrapper<AssetItem> qw = new QueryWrapper<>();
        qw.select("sum(buy_price) as buyPrice");
        qw.eq("del_flag",0);
        qw.eq("category_id",categoryId);

        AssetItem one = assetItemMapper.selectOne(qw);
        if (one == null) {
            return BigDecimal.ZERO;
        }
        return one.getBuyPrice();
    }
}
